package com.aixuexiao.web.controller;


import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aixuexiao.model.Active;
import com.aixuexiao.model.Classes;
import com.aixuexiao.model.Club;
import com.aixuexiao.model.ExamMark;
import com.aixuexiao.model.Grid;
import com.aixuexiao.model.Prize;
import com.aixuexiao.model.PrizeActive;
import com.aixuexiao.model.Score;
import com.aixuexiao.model.ScoreNote;
import com.aixuexiao.model.Student;
import com.aixuexiao.model.StudentClub;
import com.aixuexiao.model.StudentMessage;
import com.aixuexiao.service.ActiveService;
import com.aixuexiao.service.PrizeActiveService;
import com.aixuexiao.service.PrizeNoteService;
import com.aixuexiao.service.PrizeService;
import com.aixuexiao.service.ScoreNoteService;
import com.aixuexiao.service.ScoreService;
import com.aixuexiao.service.StudentClubService;
import com.aixuexiao.service.StudentService;
import com.aixuexiao.util.DateUtils;
import com.weixin.sdk.util.MessageUtil;

/**
 * 包含员工列表菜单内的所有操作
 */
@Controller()
public class StudentController {
	public static final int pagesize = 8;
	
	@Resource(name="studentService")
	private StudentService studentService;
	@Resource(name="studentClubService")
	private StudentClubService studentClubService;
	@Resource(name="activeService")
	private ActiveService activeService;
	@Resource(name="scoreService")
	private ScoreService scoreService;
	@Resource(name="scoreNoteService")
	private ScoreNoteService scoreNoteService;
	@Resource(name="prizeNoteService")
	private PrizeNoteService prizeNoteService;
	@Resource(name="prizeActiveService")
	private PrizeActiveService prizeActiveService;
	@Resource(name="prizeService")
	private PrizeService prizeService;
	
	@RequestMapping(value="/manager/students")
	public ModelAndView listStudent(String pagenum,HttpServletRequest request){
		Student student = new Student();
		String id = request.getParameter("id");
		if(!StringUtils.isEmpty(id))
			student.setId(Integer.parseInt(id));
		String classid = request.getParameter("classid");
		if(!StringUtils.isEmpty(classid))
			student.setClassid(Integer.parseInt(classid));
		student.setName(request.getParameter("name"));
		student.setRemark(request.getParameter("remark"));
		ModelAndView mv=new ModelAndView();
		mv.setViewName("students");
		mv.addObject("sidebar","students");
		int num = 1;
		if(null!=pagenum && !StringUtils.isEmpty(pagenum)){
			num = Integer.parseInt(pagenum);
		}
		List<Student> list = studentService.listStudent((num-1)*pagesize, pagesize,student);
		int count = studentService.countStudent(student);
		List<Classes> clslist = studentService.findAllClasses();
		Grid<Student> grid = new Grid<Student>();
		grid.setRows(list);
		grid.setTotal(count);
		grid.setCurrentPage(num);
		grid.setPageNum(pagesize);
		mv.addObject("grid",grid);
		mv.addObject("clsList", clslist);
		mv.addObject("length", list.size());
		mv.addObject("student", student);
		if(student.getId()!=0)
		mv.addObject("studentId",student.getId());
		return mv;
	}

	
	@RequestMapping(value="/manager/leavemessage",method=RequestMethod.GET)
	public ModelAndView leavemessage(int studentid){
		ModelAndView mv=new ModelAndView();
		Student student = studentService.findStudentById(studentid);
		if(null == student){
			mv.setViewName("redirect:/manager/students");
		}else{
			mv.setViewName("addstudentmessage");
			mv.addObject("sidebar","students");
			mv.addObject("student",student);
			List<StudentMessage> list = studentService.listMessageByStudentId(studentid, 100);
			mv.addObject("studentMessageList", list);
		}
		return mv;
	}
	/**   
	 * @Title: liuyan   
	 * @Description: 留言 
	 * @param request
	 * @return
	 * @author  author
	 */
	@RequestMapping(value="/liuyan")
	public ModelAndView liuyan(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工留言页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				isAuth = true;
				mv.addObject("student",student);
				mv.setViewName("liuyan");
				request.getSession().setAttribute("user", student.getName());
			}
		}
		if(!isAuth){//跳转登陆页面进行认证
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	/**   
	 * @Title: shenqing   
	 * @Description: 申请
	 * @param request
	 * @return
	 * @author  author
	 */
	@RequestMapping(value="/shenqing")
	public ModelAndView shenqing(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工留言页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				String cid = request.getParameter("cid");
				//查看员工是否已申请过改俱乐部，如果申请不进入sucess2页面，提示申请成功请耐心等待审核
				isAuth = true;
				try{
					int clubid = Integer.parseInt(cid);
					Club club = studentService.findClubById(clubid);
					if(club==null) throw new RuntimeException("俱乐部不存在");
					StudentClub studentclub = studentClubService.findStudentClubCount(student.getId(),clubid);
					if(studentclub==null){//该员工从未申请过该俱乐部
						//查询俱乐部放入
						mv.addObject("club", club);
						mv.addObject("student",student);
						mv.setViewName("shenqing");
					}else if(studentclub.getStatus()==1){//员工已申请了该俱乐部
						mv.setViewName("sucess2");
						mv.addObject("message", "您的申请未通过");
					}else{
						//根据俱乐部查询最新的活动记录
						Active active = activeService.findActiveByClub(clubid);
						String des = "该俱乐部下还未发布活动信息";
						if(active!=null){
							des = active.getName();
						}
						mv.setViewName("sucess2");
						mv.addObject("message", "你的申请已通过  "+des);
					}
				}catch(Exception e){
					e.printStackTrace();
					mv.setViewName("redirect:http://www.henro.cn/index.php?g=Wap&m=Index&a=content&token=frbeev1454049984&id=4027");
					mv.addObject("message", "未找到对应的俱乐部！");
				}
				
			}
		}
		if(!isAuth){//跳转登陆页面进行认证
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	@RequestMapping(value="/qiandaopage")
	public ModelAndView qiandaopage(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工签到页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				int userid = student.getId();
				isAuth = true;
				mv.addObject("student",student);
				mv.setViewName("qiandao");
				mv.addObject("score",scoreService.getScoreById(userid));//用户积分
				List<Map<String,Object>> list = scoreNoteService.getMonthScoreNoteById(userid,null);
				mv.addObject("days",list.size());//用户当月签到天数
				mv.addObject("list",JSONArray.fromObject(list).toString());
				//是否签到
				boolean isqiandao = scoreNoteService.isTodayScore(userid);
				mv.addObject("isqiandao",isqiandao);
			}
		}
		if(!isAuth){//跳转登陆页面进行认证
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	@RequestMapping(value="/qiandao")
	public ModelAndView qiandao(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工签到页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){//查询员工的积分信息
				int userid = student.getId();
				
				//是否签到
				boolean isqiandao = scoreNoteService.isTodayScore(userid);
				if(!isqiandao){//未签到
					Score score = scoreService.findScoreByUserId(userid);
					int scoreNum = scoreService.getScoreRule(userid);
					if(score==null){//没有积分信息添加用户积分信息
						score = new Score();
						score.setScore(scoreNum);
						score.setUserid(userid);
						scoreService.addScore(score);
					}else{//更新用户积分
						score.setScore(scoreNum);
						scoreService.updateScore(score);
					}
					//添加用户签到记录
					ScoreNote scoreNote = new ScoreNote();
					scoreNote.setUserid(userid);
					scoreNote.setScore(scoreNum);
					scoreNote.setDay(new Date());
					scoreNoteService.addScoreNote(scoreNote);
					isqiandao = true;
				}
				//跳转页面
				isAuth = true;
				mv.addObject("student",student);
				mv.setViewName("qiandao");
				mv.addObject("score",scoreService.getScoreById(student.getId()));//用户积分
				List<Map<String,Object>> list = scoreNoteService.getMonthScoreNoteById(student.getId(),null);
				mv.addObject("days",list.size());//用户当月签到天数
				mv.addObject("list",JSONArray.fromObject(list).toString());
				mv.addObject("isqiandao",isqiandao);
			}
		}
		if(!isAuth){//跳转登陆页面进行认证
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	@RequestMapping(value="/qiandaodays")
	@ResponseBody
	public String qiandaodays(HttpServletRequest request){
		JSONObject obj = new JSONObject();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工签到页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){//查询员工的积分信息
				isAuth = true;
				int userid = student.getId();
				Date date = null;
				try {
					String year = request.getParameter("year");
					String month = String.format("%02d", Integer.parseInt(request.getParameter("month")));
					date = DateUtils.strToDate(year+"-"+month,"yyyy-MM");
				} catch (Exception e) {
				}
				List<Map<String,Object>> list = scoreNoteService.getMonthScoreNoteById(userid,date);
				obj.put("list",JSONArray.fromObject(list).toString());
			}
		}
		obj.put("sucess", isAuth);
		if(!isAuth){//跳转登陆页面进行认证
			obj.put("message", "您好，您还未认证！");
		}
		return obj.toString();
	}
	
	@RequestMapping(value="/choujiangpage")
	public ModelAndView choujiangpage(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工抽奖页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				isAuth = true;
				mv.addObject("student",student);
				mv.setViewName("choujiang");
				//查询抽奖的活动信息
				PrizeActive prizeActive = prizeActiveService.findOnPrizeActive();
				if(prizeActive==null){//暂无活动
				    mv.setViewName("noactive");
				    return mv;
				}
				mv.addObject("prizeActive",prizeActive);
				//查询奖品列表
				Prize prize = new Prize();
				prize.setPrizeactiveid(prizeActive.getId());
				List<Prize> prizeList = prizeService.listPrize(0, 4, prize);
				mv.addObject("prizeList",prizeList);
				int jpsl = getPrizeSum(prizeList);
				mv.addObject("jpsl",jpsl);
				//查看用户是否已抽过奖
				int userid = student.getId();
				mv.addObject("hasPrized",prizeNoteService.isPrizeNoteByUserid(userid));
			}
		}
		if(!isAuth){//跳转登陆页面进行认证
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	@RequestMapping(value="/choujiang")
	@ResponseBody
	public String choujiang(HttpServletRequest request){
		JSONObject obj = new JSONObject();
		String openId = MessageUtil.getWeixinOpenId(request);
		boolean isAuth = false;//未认证
		Student student = null;
		if(!StringUtils.isEmpty(openId)){//跳转到员工抽奖页面
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				isAuth = true;
				int prizeid = Integer.parseInt(request.getParameter("prizeid"));
				int paid = Integer.parseInt(request.getParameter("paid"));
				boolean hasPrized = prizeNoteService.savePrizeDetail(student.getId(), prizeid,paid);
				obj.put("hasPrized",hasPrized);
			}
		}
		obj.put("sucess", isAuth);
		if(!isAuth){//跳转登陆页面进行认证
			obj.put("message", "您好，您还未认证！");
		}
		return obj.toString();
	}
	/**   
	 * @Title: addJulebusq   
	 * @Description: 俱乐部申请提交
	 * @param studentMessage
	 * @return
	 * @author  author
	 */
	 
	@RequestMapping(value="/julebusq")
	public ModelAndView addJulebusq(StudentClub studentClub){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("sucess2");
		mv.addObject("studentid",studentClub.getStudentid());
		studentClub.setInserttime(new Date());
		studentService.addStudentClub(studentClub);
		mv.addObject("message","申请成功请耐心等待审核");
		return mv;
	}
	/**   
	 * @Title: addWeixinmessage   
	 * @Description: 用户留言
	 * @param studentMessage
	 * @return
	 * @author  author
	 */
	 
	@RequestMapping(value="/addWeixinmessage")
	public ModelAndView addWeixinmessage(StudentMessage studentMessage){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("sucess3");
		mv.addObject("studentid",studentMessage.getStudentid());
		studentMessage.setInserttime(new Date());
		studentService.addStudentMessage(studentMessage);
		mv.addObject("message","留言成功");
		return mv;
	}
	@RequestMapping(value="/manager/examdetail",method=RequestMethod.GET)
	public ModelAndView examdetail(int studentid){
		ModelAndView mv=new ModelAndView();
		Student student = studentService.findStudentById(studentid);
		if(null == student){
			mv.setViewName("redirect:/manager/students");
		}else{
			mv.setViewName("examdetail");
			mv.addObject("sidebar","students");
			mv.addObject("student",student);
			List<ExamMark> list = studentService.findExamMarkByStudentId(studentid, 100);
			mv.addObject("emlist", list);
		}
		return mv;
	}
	
	@RequestMapping(value="/manager/addmessage")
	public ModelAndView addmessage(StudentMessage studentMessage){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("redirect:/manager/leavemessage");
		mv.addObject("studentid",studentMessage.getStudentid());
		studentMessage.setInserttime(new Date());
		studentService.addStudentMessage(studentMessage);
		mv.addObject("notice","留言成功");
		return mv;
	}
	
	@RequestMapping(value="/manager/deletemessage",method=RequestMethod.GET)
	public ModelAndView deletemessage(int studentid,int messageid){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("redirect:/manager/leavemessage");
		mv.addObject("studentid",studentid);
		studentService.deleteStudentMessageById(messageid);
		mv.addObject("notice","删除成功");
		return mv;
	}
	
	/**
	 * 分析出所有的奖品数量
	 * @param list
	 * @return
	 */
	private int getPrizeSum(List<Prize> list){
		int sum = 0;
		if(list!=null && list.size()>0){
			for(Prize prize : list){
				sum += prize.getNum();
			}
		}
		return sum;
	}
}
